<!--
 * @Descripttion: 基本信息表单
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2021-06-03 11:00:20
 * @LastEditTime: 2022-12-07 16:10:41
 * @Param {Void}
 * @Example <basic></basic>
 * @FilePath: \cscec-pms-admin\src\views\Legal\branchContract\otherTypesContract\components\Basic.vue
-->
<template>
  <a-spin :spinning="loading">
    <!-- 基本信息 -->
    <a-card :bordered="false">
      <title-name title="基本信息" />
      <custom-form
        ref="form0"
        :is-validate="true"
        :edit-model="''"
        :rules="rules[0]"
        :form="form[0]"
        :form-list="formOption[0]"
        @onSelectChange="changeDate"
      />
    </a-card>
    <!-- 基本信息 -->
    <!-- 项目部评审人员 -->
    <a-card
      v-if="hierarchy(1)"
      :bordered="false"
    >
      <title-name title="项目部评审人员" />
      <custom-form
        ref="form1"
        :is-validate="true"
        :edit-model="''"
        :rules="rules[1]"
        :form="form[1]"
        :form-list="formOption[1]"
      />
    </a-card>
    <!-- 项目部评审人员 -->
    <!-- 分公司评审人员 -->
    <a-card
      v-if="hierarchy(2)"
      :bordered="false"
    >
      <title-name title="分公司评审人员" />
      <custom-form
        ref="form2"
        :is-validate="true"
        :edit-model="''"
        :rules="rules[2]"
        :form="form[2]"
        :form-list="formOption[2]"
      />
    </a-card>
    <!-- 分公司评审人员 -->
    <!-- 公司评审人员 -->
    <a-card :bordered="false">
      <title-name title="公司评审人员" />
      <custom-form
        ref="form3"
        :is-validate="true"
        :edit-model="''"
        :rules="rules[3]"
        :form="form[3]"
        :form-list="formOption[3]"
      />
    </a-card>
    <!-- 公司评审人员 -->
    <!-- 附件 -->
    <a-card :bordered="false">
      <title-name title="附件" />
      <UploadTableNew
        ref="uploadTable"
        :disabled="type==='detail'"
        :mode="file.mode"
        :init-file-list="file.fileList"
        :need-page="file.needPage"
        :business-code="file.businessCode"
      />
    </a-card>
    <!-- 附件 -->
    <!-- 底部按钮 -->
    <div v-if="!isConsultation" class="tool-btns page-btn-right-top">
      <base-print-button
        v-if="isDisabled&&!$route.query.taskDefKey && !$route.query.hasOwnProperty('procInstId')"
        type="primary"
        :before-print-fn="handlePrint"
      />
      <a-button
        v-if="!isDisabled"
        class="ml12"
        type="primary"
        :loading="submitLoading"
        @click="handleSubmit('DRAFT')"
      >
        保存草稿
      </a-button>
      <a-button
        v-if="!isDisabled"
        class="ml12"
        type="primary"
        :loading="submitLoading"
        @click="handleSubmit('SUBMITTED')"
      >
        提交
      </a-button>
      <a-button
        class="ml12"
        type="default"
        @click="handleClose"
      >
        关闭
      </a-button>
    </div>
    <!-- 底部按钮 -->
    <selectApprover
      :businessId="businessId"
      :processConfig="setProcessConfig"
    ></selectApprover>
  </a-spin>
</template>
<script>
import SelectUndertaking from '@/components/Select/SelectUndertaking'
import otherTypesContract from '@/api/legal/branchContract/otherTypesContract'
import Moment from 'moment'
import SelectCompanyAndProject from '@/components/Select/SelectCompanyAndProject'
import BasePrintButton from '@/components/BasePrintButton'

export default {
  name: 'Basic',
  props: {
    type: {
      type: String,
      require: true
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  components: {
    BasePrintButton
  },
  data() {
    return {
      // 接口响应代码
      resCode: 200,
      // 页面加载
      loading: false,
      //表单
      form: [
        {
          contractName: void 0,
          businessDepId: void 0,
          otherParty: void 0,
          amount: void 0,
          contractContent: void 0,
          creatorName: void 0,
          createTime: void 0
        },
        {
          businessManager: void 0,
          supervisor: void 0,
          projectManager: void 0,
          otherHeaderId: void 0
        },
        {
          businessManager: void 0,
          supervisor: void 0,
          projectManager: void 0,
          businessLeaderId: void 0,
          otherHeaderId: void 0
        },
        {
          businessManager: void 0,
          supervisor: void 0,
          legalAdviser: void 0,
          businessLeaderId: void 0,
          projectManager: void 0,
          otherHeaderId: void 0
        }
      ],
      // 登录人信息
      userInfo: JSON.parse(sessionStorage.getItem('ycloud-user_info')),
      // id
      ids: {
        // 项目部id
        PD: '',
        // 分公司id
        BC: '',
        // 公司id
        CO: '53085e2c9f1f4685801ef31994f57c49'
      },
      // 附件
      file: {
        // 处理操作的模式：'add'模式下，删除操作会调用文件删除接口，'edit'模式只会在表格中移除删除数据，不会调用接口
        mode: 'add',
        // 上传文件的业务编码
        businessCode: 'LCM08',
        // 是否需要分页
        needPage: false,
        // 初始化文件列表
        fileList: []
      },
      // 表单提交loading
      submitLoading: false,
      // 打印loading
      printLoading: false,
      //字典
      dicts: {},
      // 提交表单
      submitForm: {},
      // 表单索引
      index: [],
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  computed: {
    // 表单禁用
    isDisabled() {
      return this.type === 'detail'
    },
    // 表单配置
    formOption() {
      return [
        // 基本信息
        [
          {
            label: '合同名称',
            keyName: 'contractName',
            type: 'BaseInput',
            disabled: this.isDisabled,
            span: 24,
            rules: [{ required: true, message: '请输入', trigger: 'change' }]
          },
          {
            label: '业务主办单位',
            keyName: 'businessDepId',
            type: SelectCompanyAndProject,
            attrs: {
              autoSelect: true
            },
            disabled: true
          },
          {
            label: '合同对方',
            keyName: 'otherParty',
            type: 'BaseInput',
            disabled: this.isDisabled,
            rules: [{ required: true, message: '请输入', trigger: 'change' }]
          },
          {
            label: '合同价(万元)',
            keyName: 'amount',
            type: 'BaseInputNumber',
            disabled: this.isDisabled,
            attrs: {
              formatter: this.limitNumber,
              parser: this.limitNumber
            },
            rules: [{ required: true, message: '请输入', trigger: 'change' }]
          },
          {
            label: '合同简要内容',
            keyName: 'contractContent',
            type: 'BaseTextarea',
            disabled: this.isDisabled,
            attrs: {
              maxLength: 1000
            },
            autoSize: { minRows: 3, maxRows: 7 },
            span: 24,
            rules: [{ required: true, message: '请输入', trigger: 'change' }]
          },
          {
            label: '创建人',
            keyName: 'creatorName',
            type: 'BaseInput',
            disabled: true
          },
          {
            label: '创建时间',
            keyName: 'createTime',
            type: 'BaseInput',
            disabled: true
          }
        ],
        // 项目部评审人员
        [
          {
            label: '商务经理',
            keyName: 'businessManager',
            type: 'BaseInput',
            disabled: true
          },
          {
            label: '财务主管',
            keyName: 'supervisor',
            type: 'BaseInput',
            disabled: true
          },
          {
            label: '项目经理',
            keyName: 'projectManager',
            type: 'BaseInput',
            disabled: true
          },
          {
            label: '其他涉及部门负责人',
            keyName: 'otherHeaderId',
            placeholder: '请选择',
            type: SelectUndertaking,
            attrs: {
              mode: 'multiple',
              orgId: this.ids.PD
            },
            disabled: this.isDisabled,
            span: 24
          }
        ],
        // 分公司评审人员
        [
          {
            label: '商务法务部经理',
            keyName: 'businessManager',
            type: 'BaseInput',
            disabled: true
          },
          {
            label: '财务资金部经理',
            keyName: 'supervisor',
            type: 'BaseInput',
            disabled: true
          },
          {
            label: '分公司总经济师',
            keyName: 'projectManager',
            type: 'BaseInput',
            disabled: true
          },
          {
            label: '分公司业务分管领导',
            keyName: 'businessLeaderId',
            type: SelectUndertaking,
            placeholder: '请选择',
            attrs: {
              allowClear: true,
              orgId: this.ids.BC,
              isInclude: true,
              isDefault: false,
              requestParams: { and: true, orgType: '2' }
            },
            disabled: this.isDisabled,
            rules: [{ required: true, message: '请选择', trigger: 'change' }]
          },
          {
            label: '其他涉及部门负责人',
            keyName: 'otherHeaderId',
            placeholder: '请选择',
            type: SelectUndertaking,
            attrs: {
              mode: 'multiple',
              orgId: this.ids.BC
            },
            disabled: this.isDisabled,
            span: 24
          }
        ],
        // 公司评审人员
        [
          {
            label: '合约法务部经理',
            keyName: 'businessManager',
            type: 'BaseInput',
            disabled: true
          },
          {
            label: '财务资金部经理',
            keyName: 'supervisor',
            type: 'BaseInput',
            disabled: true
          },
          {
            label: '公司总法律顾问',
            keyName: 'legalAdviser',
            type: 'BaseInput',
            disabled: true
          },
          {
            label: '公司业务分管领导',
            keyName: 'businessLeaderId',
            type: SelectUndertaking,
            placeholder: '请选择',
            attrs: {
              allowClear: true,
              orgId: this.ids.CO,
              isInclude: true,
              isDefault: false,
              requestParams: { and: true, orgType: '2' }
            },
            disabled: this.isDisabled,
            rules: [{ required: true, message: '请选择', trigger: 'change' }]
          },
          {
            label: '公司总经济师',
            keyName: 'projectManager',
            type: 'BaseInput',
            disabled: true
          },
          {
            label: '其他涉及部门负责人',
            keyName: 'otherHeaderId',
            type: SelectUndertaking,
            placeholder: '请选择',
            attrs: {
              mode: 'multiple',
              orgId: this.ids.CO
            },
            disabled: this.isDisabled,
            span: 24
          }
        ]
      ]
    },
    // 校验
    rules() {
      const arr = []
      this.formOption.forEach((el) => {
        let obj = {}
        el.forEach((item) => {
          if (item.rules) {
            obj[item.keyName] = item.rules
          }
        })
        arr.push(obj)
      })
      return arr
    }
  },
  async created() {
    this.getHierarchy()
    this.getDate()
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('legal_other_review_new')
  },
  methods: {
    /**
     * @description: 获取带出数据
     * @param {Void}
     * @return {Void}
     */
    async getDate() {
      this.loading = true
      // 创建人
      this.form[0].creatorName = this.userInfo.name
      // 创建时间
      this.form[0].createTime = Moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
      // 获取组织架构
      const info = await otherTypesContract.findOrg()
      info.data.forEach((el, index) => {
        this.form[index + 1] = Object.assign(this.form[index + 1], el)
      })
      console.log(info)
      // 回显数据
      if (this.type !== 'add') {
        try {
          const { data } = await otherTypesContract.findListByMainId({ id: this.$route.query.id })
          // id
          this.form[0].id = data.id
          this.detailHierarchy(data)
          // 写入对应的form
          this.form.forEach((el, index) => {
            if (this.index.includes(index)) {
              Object.keys(el).forEach((item) => {
                el[item] = data[item] || el[item]
              })
            }
          })
          // 项目部
          if (data.otherContractProjectDTO !== null) {
            Object.keys(this.form[1]).forEach((item) => {
              this.form[1][item] = data.otherContractProjectDTO[item] || this.form[1][item]
            })
            this.form[1].otherHeaderId = data.otherContractProjectDTO.otherHeaderId?.map((el) => {
              return {
                key: el.keyId,
                label: el.label
              }
            })
          }
          // 分公司
          if (data.otherContractBranchDTO !== null) {
            const obj = data.otherContractBranchDTO.businessLeaderId
            Object.keys(this.form[2]).forEach((item) => {
              this.form[2][item] = data.otherContractBranchDTO[item] || this.form[1][item]
            })
            if (obj) {
              this.form[2].businessLeaderId = {
                key: obj.keyId,
                label: obj.label
              }
            }
            this.form[2].otherHeaderId = data.otherContractBranchDTO.otherHeaderId?.map((el) => {
              return {
                key: el.keyId,
                label: el.label
              }
            })
          }
          // 公司
          const obj1 = data.otherContractCompanyDTO.businessLeaderId
          if (obj1) {
            this.form[3].businessLeaderId = {
              key: obj1.keyId,
              label: obj1.label
            }
          }
          this.form[3].otherHeaderId = data.otherContractCompanyDTO.otherHeaderId?.map((el) => {
            return {
              key: el.keyId,
              label: el.label
            }
          })
          // 附件
          this.file.fileList = data.fileInfoVos || []
        } catch (error) {
          console.log(error)
        }
      }
      this.loading = false
    },
    /**
     * @description: 数据对应层级
     * @param {Object} 表达回显数据
     * @return {Void}
     */
    detailHierarchy(data) {
      if (this.type === 'detail') {
        if (data.otherContractProjectDTO !== null) {
          this.index.push(1)
        }
        if (data.otherContractBranchDTO !== null) {
          this.index.push(2)
        }
      }
    },
    /**
     * @description: 登录人对应层级
     * @param {Void}
     * @return {Void}
     */
    getHierarchy() {
      this.index = [0, 3]
      // 不是查看
      if (this.type !== 'detail') {
        // 项目部
        if (this.userInfo.currentPost.code === 'PD') {
          this.index.push(1)
          this.index.push(2)
          // 带上项目id和分公司id
          this.submitForm.projectId = this.userInfo.currentPost.id
          this.submitForm.branchCompanyId = this.userInfo.currentPost.orgId
          // 写入id
          this.ids.PD = this.userInfo.currentPost.id
          this.ids.BC = this.userInfo.currentPost.orgId
        }
        // 分公司
        if (this.userInfo.currentPost.code === 'BC') {
          this.index.push(2)
          //带上分公司id
          this.submitForm.branchCompanyId = this.userInfo.currentPost.id
          // 写入id
          this.ids.BC = this.userInfo.currentPost.id
        }
      }
    },
    /**
     * @description: 登录人对应层级显示表单
     * @param {Number} index 表单索引
     * @return {Void}
     */
    hierarchy(index) {
      return this.index.indexOf(index) > 0
    },
    /**
     * @description: 获取附件列表
     * @param {Array} list 附件列表
     * @return {Void}
     */
    fileArrysData(list) {},
    /**
     * @description: 打印
     * @param {Void}
     * @return {Void}
     */
    async handlePrint() {
      const {
        data: { content }
      } = await otherTypesContract.otherContractPrint({ baseId: this.$route.query.id })
      return content
    },
    /**
     * @description: 提交表单
     * @param {String} type 提交类型
     * @return {Void}
     */
    async handleSubmit(type) {
      this.setProcessConfig = null
      this.submitForm.fileInfoVos = this.file.fileList
      this.index.forEach((el) => {
        // 项目部
        if (el === 1) {
          const obj = Object.assign({}, this.form[1])
          obj.otherHeaderId = (obj.otherHeaderId || []).map((el) => {
            return {
              keyId: el.key,
              label: el.label
            }
          })
          this.submitForm.otherContractProjectDTO = obj
        }
        // 分公司
        if (el === 2) {
          const obj = Object.assign({}, this.form[2])
          obj.businessLeaderId = obj?.businessLeaderId?.key
            ? {
                keyId: obj.businessLeaderId.key,
                label: obj.businessLeaderId.label
              }
            : null
          obj.otherHeaderId = (obj.otherHeaderId || []).map((el) => {
            return {
              keyId: el.key,
              label: el.label
            }
          })
          this.submitForm.otherContractBranchDTO = obj
        }
        // 公司
        if (el === 3) {
          const obj = Object.assign({}, this.form[3])
          obj.businessLeaderId = obj?.businessLeaderId?.key
            ? {
                keyId: obj.businessLeaderId.key,
                label: obj.businessLeaderId.label
              }
            : null
          obj.otherHeaderId = (obj.otherHeaderId || []).map((el) => {
            return {
              keyId: el.key,
              label: el.label
            }
          })
          this.submitForm.otherContractCompanyDTO = obj
        }
      })
      // 保存草稿
      if (type === 'DRAFT') {
        this.submitLoading = true
        this.submitForm.reviewAuditStatus = 'DRAFT'
        const data = Object.assign({}, this.submitForm, this.form[0])
        if (this.form[0].id) {
          otherTypesContract
            .editByMain(data)
            .then(({ code, message }) => {
              if (code === this.resCode) {
                this.$message.success('保存成功')
              } else {
                this.$message.warning(message)
              }
            })
            .finally(() => {
              this.submitLoading = false
            })
        } else {
          otherTypesContract
            .createByMain(data)
            .then(({ code, data: { id }, message }) => {
              if (code === this.resCode) {
                this.$message.success('保存成功')
                this.form[0].id = id
              } else {
                this.$message.warning(message)
              }
            })
            .finally(() => {
              this.submitLoading = false
            })
        }
      }
      // 提交
      if (type === 'SUBMITTED') {
          const validate = this.index.map((el) => {
            let isValidate = false
            this.$refs['form' + el].validate((valid) => {
              if (valid) {
                isValidate = true
              } else {
                this.$message.warning('请填写完所有必填项信息')
              }
            })
            return isValidate
          })
        if (validate.indexOf(false) < 0) {
        this.submitApprovalConfirm(this.processConfig, async (flag) => {
          if(!flag) {
            this.submitLoading = false
            return
          }
            this.submitLoading = true
            if (this.submitForm.fileInfoVos.length <= 0) {
              this.$message.warning('请上传附件')
              this.submitLoading = false
              return
            }
            // 是否有id,有直接提交，没有先保存再提交
            if (this.form[0].id) {
              this.submitForm.reviewAuditStatus = 'SUBMITTED'
              const data = Object.assign({}, this.submitForm, this.form[0])
              try {
                const { code } = await otherTypesContract.editByMain(data)
                // 提交
                const res = await otherTypesContract.generalSubmit({
                  auditStatusEnum: 'SUBMITTED',
                  baseId: this.form[0].id,
                  // deptType:'' 待确认 PD BD CO
                })
                if (code === this.resCode && res.code === this.resCode) {
                  this.$message.success('提交成功')
                  this.businessId = res.data.id
                  this.setProcessConfig = this.processConfig
                } else {
                  this.$message.warning(res.message)
                }
                this.submitLoading = false
              } catch (error) {
                console.log(error)
              }
            } else {
              try {
                // 保存
                this.submitForm.reviewAuditStatus = 'SUBMITTED'
                const data = Object.assign({}, this.submitForm, this.form[0])
                const {
                  code: code1,
                  data: { id }
                } = await otherTypesContract.createByMain(data)
                this.form[0].id = id

                // 提交
                const res = await otherTypesContract.generalSubmit({
                  auditStatusEnum: 'SUBMITTED',
                  baseId: this.form[0].id
                })
                if (code1 === this.resCode && res.code === this.resCode) {
                  this.$message.success('提交成功')
                  this.businessId = res.data.id
                  this.setProcessConfig = this.processConfig
                } else {
                  this.$message.warning(res.message)
                }
                this.submitLoading = false
              } catch (error) {
                console.log(error)
              }
            }
        })
      }
      }
    },
    /**
     * @description: 关闭
     * @param {Void}
     * @return {Void}
     */
    handleClose() {
      this.$close()
    },
    /**
     * @description: 合同价保留两位小数
     * @param {Any} value 输入值
     * @return {Number} 合同价
     */
    limitNumber(value) {
      const reg = /^(\-)*(\d+)\.(\d\d).*$/
      if (typeof value === 'string') {
        return !isNaN(Number(value)) ? value.replace(reg, '$1$2.$3') : 0
      } else if (typeof value === 'number') {
        return !isNaN(value) ? String(value).replace(reg, '$1$2.$3') : 0
      } else {
        return 0
      }
    },
    /**
     * @description: 表单选人回调
     * @param {String} e 字段名
     * @param {Object} v 值
     * @return {Void}
     */
    changeDate(e, v) {
      // 获取业务主办单位名称
      if (e === 'businessDepId') {
        this.form[0].businessDepName = v.name
      }
    }
  }
}
</script>
<style lang="less" scoped>
</style>

